package com.paomi.client.base;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hannesdorfmann.mosby3.mvp.MvpActivity;
import com.hannesdorfmann.mosby3.mvp.MvpPresenter;
import com.hannesdorfmann.mosby3.mvp.MvpView;
import com.paomi.client.MyApplication;
import com.paomi.client.R;
import com.paomi.client.activity.net.NetNullActivity;
import com.paomi.client.bean.AppVersionBean;
import com.paomi.client.bean.UserInfo;
import com.paomi.client.bean.UserUtils;
import com.paomi.client.utils.InputMethodUtils;
import com.paomi.client.utils.MyPermissionUtils;
import com.paomi.client.utils.RxUtils;
import com.paomi.client.widget.CommonTitleView;
import com.paomi.client.widget.SystemBarHelper;
import com.paomi.client.widget.title.RxBarUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 继承mvp模式的基类
 *
 * @param <V>
 * @param <P>
 */
public abstract class BaseMvpActivity<V extends MvpView, P extends MvpPresenter<V>> extends MvpActivity<V, P> implements CommonTitleView.OnTitleItemClickListener {
    public String TAG = getClass().getSimpleName();
    protected boolean jumpNet = false;
    private Unbinder unbinder;
    protected CommonTitleView mTitleView;
    public Typeface iconfont;
    public static final String UPDATEVERSION_RECEIVER = "com.paomi.clent.UPDATEVERSION_RECEIVER";

    public CommonTitleView getTitleView() {
        return mTitleView;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        iconfont = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        /**
         *  需要在调用{@link BaseMvpAct#setContentView(int)}之前调用
         */
        //设置StatusBar透明
        SystemBarHelper.immersiveStatusBar(this, 0);
        SystemBarHelper.setStatusBarDarkMode(this);
//        setStatueBar();
        setContentView(getLayoutId());
        getPresenterExtra();
        unbinder = ButterKnife.bind(this);
        RxUtils.init(this);
        mTitleView = (CommonTitleView) findViewById(R.id.title_view);
        if (mTitleView != null) mTitleView.setOnTitleItemClickListener(this);
        TextView textview_title = (TextView) findViewById(R.id.textview_title);
        if (textview_title != null) {
            textview_title.setText(setTitle());
        }
        TextView button_goback = (TextView) findViewById(R.id.button_goback);
        if (button_goback != null) {
            showBack(button_goback);
            button_goback.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
        initEvent();
    }

    /**
     * 初始化Presenter需要的参数
     */
    protected void getPresenterExtra() {

    }

    protected abstract String setTitle();

    protected abstract void showBack(TextView button_goback);

    public UserInfo getUserInfo() {
        return UserUtils.getInstance().getUserInfo();
    }

    protected boolean getBooleanExtra(String key) {
        Bundle extras = getIntent().getExtras();
        return extras != null && extras.getBoolean(key, false);
    }

    /**
     * 需要改变状态栏颜色重写此方法
     */
    protected void setStatueBar() {
        RxBarUtils.setStatusBarColor(this, R.color.main_color);
    }

    @NonNull
    protected abstract @LayoutRes
    int getLayoutId();

    protected abstract void initEvent();
    /**
     * 标题左边点击事件，默认关闭，需要特殊处理重写{@link #onLeftClick()}
     */

    /**
     * 标题左边点击事件，需要特殊处理重写此方法
     * {@link #finish()}
     */
    public void onLeftClick() {
        onBackPressed();
    }

    /**
     * 标题右边点击事件，需要点击重写此方法
     */
    public void onRightClick(View view) {
    }

    /**
     * 标题点击事件，需要点击重写此方法
     */
    @Override
    public void onTitleClick() {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (unbinder != null) {
            unbinder.unbind();
            unbinder = null;
        }
    }

//    @Bus(EventTag.emergencyCall)
//    public void emergencyCall(boolean smartL) {
//        startActivity(new Intent(this, EmergenCallActivity.class));
//    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MyPermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);//完成回调
    }

    @Override
    protected void onResume() {
        super.onResume();
//        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
//        MobclickAgent.onPause(this);
    }

    public void getIntent(Class cl) {
        Intent intent = new Intent();
        intent.setClass(this, cl);
        startActivity(intent);
    }

    public void getIntentString(Class cl, String flag) {
        Intent intent = new Intent();
        intent.putExtra("flag", flag);
        intent.setClass(this, cl);
        startActivity(intent);
    }

    public Handler getHandler() {
        return getWindow().getDecorView().getHandler();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        InputMethodUtils.hideSoftInput(this);
        return super.onTouchEvent(event);
    }

    /**
     * 带着数据，设置返回码，从本页面跳转到下个页面，重写onActivityResult可以获取从下个页面带回来的数据
     *
     * @param cls         需要跳转到的页面
     * @param obj         传递给下个页面的数据
     * @param requestCode 返回码
     */
    public void startActivityForResult(Class<?> cls, Object obj, int requestCode) {
        if (getNetworkType() == 0 && jumpNet) {
            startActivity(new Intent(this, NetNullActivity.class));
        } else {
            Intent intent = new Intent(this, cls);
            if (obj != null) {
                intent.putExtra("data", (Serializable) obj);
            }
            startActivityForResult(intent, requestCode);
        }
        overridePendingTransition(R.anim.push_right_in, R.anim.push_left_out);
    }

    public int getNetworkType() {
        int netType = 0;
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            netType = 1;
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = 2;
        }
        return netType;
    }


    protected NoticeReceiver receiver = new NoticeReceiver();
    private AppVersionBean.VersionBean updateModel=null;//版本更新服务传值数据
    private String download_url;//下载安装包的链接
    @Override
    protected void onStart() {
        super.onStart();
        //注册通知广播
        IntentFilter filter = new IntentFilter();
//        filter.addAction(NOTICE_TAKE);
        filter.addAction(UPDATEVERSION_RECEIVER);
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(receiver);
    }
    private static final int DIALOG_STATE_UPDATE = 10000;
    private static final int DIALOG_STATE_LL = 10001;//流量下下载
    private static final int DIALOG_STATE_DOWNLOAD = 10002;//无线网下载
    class NoticeReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(UPDATEVERSION_RECEIVER)) {//版本下载服务通知
                updateModel=(AppVersionBean.VersionBean) intent.getSerializableExtra("updateModel");
                if (updateModel!=null) {
                    if (updateModel.getStatus()==1) {
                        download_url = updateModel.getUrl();
                        //需要更新
                        // 当前网络状况
                        if (getNetworkType()==2) {//无线网
                            showMyDialog(DIALOG_STATE_DOWNLOAD);
                        } else {//流量
                            showMyDialog(DIALOG_STATE_LL);
                        }

                    } else if (updateModel.getStatus()==0) {
                        download_url = updateModel.getUrl();
                        showMyDialog(3);
                    }
                }
            }
        }
    }

    private Dialog dialog;//版本更新弹框
    private int curState=0;
    private int progress = 0;
    private boolean isCancel = false;
    private String saveFileName = MyApplication.PATH_SD + "PaoMi.apk";
    /**
     * 版本更新的弹出框
     */
    private void initDialog() {
        dialog = new Dialog(this, R.style.dialog03);
        dialog.setContentView(R.layout.dialog_update);
        dialog.setCancelable(false);

//        ImageView imageView = (ImageView) dialog.findViewById(R.id.dialog_title);
//        AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getBackground();
//        animationDrawable.start();
        dialog.findViewById(R.id.dialog_content).setVisibility(View.VISIBLE);
        Button leftBtn = (Button) dialog.findViewById(R.id.dialog_btn_left);
        leftBtn.setText(getResources().getString(R.string.cancel));
        leftBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                switch (curState) {
                    case DIALOG_STATE_DOWNLOAD:
                        //终止下载
                        isCancel = true;
                        break;
                    case 3:
                        break;
                }
//                LoginActivity.this.finish();
            }
        });

        Button rightBtn = (Button) dialog.findViewById(R.id.dialog_btn_right);
        rightBtn.setVisibility(View.GONE);
        rightBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (curState) {
                    case DIALOG_STATE_LL:
                        showMyDialog(DIALOG_STATE_DOWNLOAD);
                        break;
                    case 3:
                        if (getNetworkType()==2) {//无线网
                            showMyDialog(DIALOG_STATE_DOWNLOAD);
                        } else {//流量
                            showMyDialog(DIALOG_STATE_LL);
                        }
                        break;
                }
            }
        });

        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 设置宽度
        dialog.getWindow().setAttributes(lp);
    }

    private void showMyDialog(int type) {
        curState = type;

        if (dialog == null) {
            initDialog();
        }

        TextView tcontentTV;
        Button rightBtn;

        switch (type) {
            case DIALOG_STATE_UPDATE:
                tcontentTV = (TextView) dialog.findViewById(R.id.dialog_content);
                rightBtn = (Button) dialog.findViewById(R.id.dialog_btn_right);
                dialog.findViewById(R.id.update_dialog_ll_bar).setVisibility(View.GONE);
                tcontentTV.setText(getResources().getString(R.string.update_going));
                rightBtn.setVisibility(View.GONE);
                break;
            case DIALOG_STATE_LL://流量情况下
                tcontentTV = (TextView) dialog.findViewById(R.id.dialog_content);
                rightBtn = (Button) dialog.findViewById(R.id.dialog_btn_right);
                dialog.findViewById(R.id.update_dialog_ll_bar).setVisibility(View.GONE);
                tcontentTV.setText(getResources().getString(R.string.update_message));
                rightBtn.setVisibility(View.VISIBLE);
                break;
            case DIALOG_STATE_DOWNLOAD://wifi情况下直接下载
                tcontentTV = (TextView) dialog.findViewById(R.id.dialog_content);
                rightBtn = (Button) dialog.findViewById(R.id.dialog_btn_right);
                if (isCheckPermisson(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    tcontentTV.setGravity(Gravity.LEFT);
                    tcontentTV.setText(updateModel.getContent());
                    dialog.findViewById(R.id.update_dialog_ll_bar).setVisibility(View.VISIBLE);
                    rightBtn.setVisibility(View.GONE);
                    downloadAPK(download_url);
                } else {
                    tcontentTV.setVisibility(View.VISIBLE);
                    tcontentTV.setText(getResources().getString(R.string.update_admin));
                    dialog.findViewById(R.id.update_dialog_ll_bar).setVisibility(View.GONE);
                    rightBtn.setVisibility(View.GONE);
                }
                break;
            case 1:
                //更新应用失败
                dialog.findViewById(R.id.update_dialog_ll_bar).setVisibility(View.GONE);
                tcontentTV = (TextView) dialog.findViewById(R.id.dialog_content);
                tcontentTV.setText(getResources().getString(R.string.update_failure));
                break;
            case 2:
                //下载应用失败
                dialog.findViewById(R.id.update_dialog_ll_bar).setVisibility(View.GONE);
                tcontentTV = (TextView) dialog.findViewById(R.id.dialog_content);
                tcontentTV.setText(getResources().getString(R.string.update_call));
                break;
            case 3://有更新，不强制更新
                tcontentTV = (TextView) dialog.findViewById(R.id.dialog_content);
                rightBtn = (Button) dialog.findViewById(R.id.dialog_btn_right);
                dialog.findViewById(R.id.update_dialog_ll_bar).setVisibility(View.GONE);
//                dialog.findViewById(R.id.hint_log).setVisibility(View.VISIBLE);
//                tcontentTV.setText(getResources().getString(R.string.update_get));
                tcontentTV.setText(getResources().getString(R.string.update_get)+"\n"+"\n"+updateModel.getContent());
                rightBtn.setVisibility(View.VISIBLE);
                break;
        }
        if (dialog != null && !dialog.isShowing()) {
            dialog.show();
        }
    }

    /**
     * 下载apk的线程
     */
    public void downloadAPK(final String apkUrl) {

        //显示dialog
        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    URL url = new URL(apkUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();

                    int length = conn.getContentLength();
                    InputStream is = conn.getInputStream();

                    File file = new File(MyApplication.PATH_SD);
                    if (!file.exists()) {
                        file.mkdirs();
                    }


                    String apkFile = saveFileName;
                    File ApkFile = new File(apkFile);
                    FileOutputStream fos = new FileOutputStream(ApkFile);

                    int count = 0;
                    byte buf[] = new byte[1024];
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        progress = (int) (((float) count / length) * 100);
                        Message message1 = new Message();
                        message1.what = 100;
                        handler.sendMessage(message1);
                        // 更新进度
                        if (numread <= 0) {
                            // 下载完成通知安装
                            Message message = new Message();
                            message.what = 1000;
                            handler.sendMessage(message);
                            break;
                        }
                        if (count != -1) {
                            fos.write(buf, 0, numread);
                        }
                    } while (!isCancel); // 点击取消就停止下载.

                    fos.close();
                    is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    Message message1 = new Message();
                    message1.what = 2;
                }
            }
        }).start();
    }


    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 1000:
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    Intent intent = getAPKFileIntent(saveFileName);
                    startActivity(intent);
                    break;
                case 100:
                    if (dialog != null && dialog.isShowing()) {
                        ProgressBar progressBar = (ProgressBar) dialog.findViewById(R.id.myProgressBar);
                        progressBar.setProgress(progress);
                        TextView persent = (TextView) dialog.findViewById(R.id.update_dialog_tv_bar);
                        persent.setText(progress + "%");
                    }
                    break;
                case 2:
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            showMyDialog(2);
                        }
                    }, 500);
                    break;
                default:
            }
            return false;
        }
    });

    public Intent getAPKFileIntent(String path) {
        Intent i = new Intent(Intent.ACTION_VIEW);
//        i.addCategory(Intent.CATEGORY_DEFAULT);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        File apkFile = new File(path);
        i.setDataAndType(Uri.parse("file://" + apkFile.toString()), "application/vnd.android.package-archive");
        return i;
    }
    protected boolean isCheckPermisson(String permission) {
        if (ContextCompat.checkSelfPermission(getApplicationContext(), permission) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        return false;
    }
}
